package com.xy.xylive.aop;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdviceAdapter;

import com.xy.xylive.common.AESUtil;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

@ControllerAdvice
@Order(2)
@Slf4j
public class DecryptRequestAspect extends RequestBodyAdviceAdapter{
    @Autowired
    private AESUtil aesUtil;

    @Override
    public boolean supports(MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return methodParameter.hasMethodAnnotation(Decrypt.class) ||
                methodParameter.hasParameterAnnotation(Decrypt.class);
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
        try {
            // 读取加密的请求体内容
            String encryptedContent = StreamUtils.copyToString(inputMessage.getBody(), StandardCharsets.UTF_8);
            log.debug("读取加密的请求体内容: " + encryptedContent);
            // 解析json字符串
            JSONObject jsonObject = JSONUtil.parseObj(encryptedContent);
            // 获取encrypt字段
            String encrypt = jsonObject.getStr("encrypt");
            // 使用AES解密
            String decryptedContent = aesUtil.decrypt(encrypt);
            // 将解密后的内容包装为新的HttpInputMessage
            return new HttpInputMessage() {
                @Override
                public InputStream getBody() throws IOException {
                    return new ByteArrayInputStream(decryptedContent.getBytes(StandardCharsets.UTF_8));
                }
                @Override
                public HttpHeaders getHeaders() {
                    return inputMessage.getHeaders();
                }
            };
        } catch (Exception e) {
            log.error("解密请求体失败", e);
            throw new IOException("解密请求体失败: " + e.getMessage(), e);
        }
    }


}
